const babelParser = require('@babel/parser')
const path = require('path')
const fs = require('fs')
const traverse = require('@babel/traverse')
const { transformFromAstSync } = require('@babel/core')
const env = require('@babel/preset-env')
const genCode = (code) => {
  return `function (require,module,exports) {${code}}`
}
const getCodeAndDepWithContent = (preCode) => {
  const ast = babelParser.parse(preCode, {
    sourceType: 'module',
  })
  const dependencies = []
  traverse.default(ast, {
    ImportDeclaration: ({ node }) => {
      // 基于 import 来获取当前文件需要的依赖
      dependencies.push(node.source.value)
    },
  })
  const { code } = transformFromAstSync(ast, preCode, {
    presets: [env],
  })
  return {
    code: genCode(code),
    dependencies,
  }
}

const getCodeAndDepWithPath = (absPath) => {
  const contet = fs.readFileSync(absPath, { encoding: 'utf-8' })
  return getCodeAndDepWithContent(contet)
}
const aaa = path.resolve(__dirname,'../src/main.js')
const res = getCodeAndDepWithPath(aaa)
console.log(res)
